<template>
  <div class="statistics-dashboard">
    <!-- 数据概览 -->
    <el-row :gutter="20" class="overview-section">
      <el-col :span="4">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background-color: #409eff;">
              <i class="el-icon-user"></i>
            </div>
            <div class="stat-info">
              <div class="stat-label">总会员数</div>
              <div class="stat-value">{{ overview.totalMembers }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background-color: #67c23a;">
              <i class="el-icon-user-solid"></i>
            </div>
            <div class="stat-info">
              <div class="stat-label">新增会员</div>
              <div class="stat-value">{{ overview.newMembers }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background-color: #e6a23c;">
              <i class="el-icon-user"></i>
            </div>
            <div class="stat-info">
              <div class="stat-label">活跃会员</div>
              <div class="stat-value">{{ overview.activeMembers }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background-color: #f56c6c;">
              <i class="el-icon-tickets"></i>
            </div>
            <div class="stat-info">
              <div class="stat-label">今日预约</div>
              <div class="stat-value">{{ overview.todayBookings }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background-color: #909399;">
              <i class="el-icon-money"></i>
            </div>
            <div class="stat-info">
              <div class="stat-label">今日收入</div>
              <div class="stat-value">¥{{ overview.todayRevenue }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background-color: #5daf34;">
              <i class="el-icon-location-outline"></i>
            </div>
            <div class="stat-info">
              <div class="stat-label">今日签到</div>
              <div class="stat-value">{{ overview.todayCheckins }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-section">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>会员增长趋势</span>
            </div>
          </template>
          <div ref="memberGrowthChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>收入统计</span>
            </div>
          </template>
          <div ref="revenueChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-section">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>课程预约统计</span>
            </div>
          </template>
          <div ref="bookingChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>签到统计</span>
            </div>
          </template>
          <div ref="checkinChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 热门数据 -->
    <el-row :gutter="20" class="popular-section">
      <el-col :span="12">
        <el-card class="popular-card">
          <template #header>
            <div class="card-header">
              <span>热门课程</span>
            </div>
          </template>
          <el-table :data="popularCourses" style="width: 100%">
            <el-table-column prop="courseName" label="课程名称" />
            <el-table-column prop="bookingCount" label="预约次数" width="120" />
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="popular-card">
          <template #header>
            <div class="card-header">
              <span>热门教练</span>
            </div>
          </template>
          <el-table :data="popularCoaches" style="width: 100%">
            <el-table-column prop="coachName" label="教练姓名" />
            <el-table-column prop="courseCount" label="授课次数" width="120" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import type {
  StatisticsOverview,
  MemberGrowthData,
  RevenueData,
  BookingData,
  CheckinData,
  PopularCourse,
  PopularCoach
} from '@/types/api/statistics'
import { statisticsApi } from '@/api/modules/statistics'

// 数据概览
const overview = ref<StatisticsOverview>({
  totalMembers: 0,
  newMembers: 0,
  activeMembers: 0,
  totalCourses: 0,
  totalBookings: 0,
  todayBookings: 0,
  totalRevenue: 0,
  monthlyRevenue: 0,
  todayRevenue: 0,
  totalCheckins: 0,
  todayCheckins: 0,
  totalCards: 0,
  activeCards: 0
})

// 图表实例
const memberGrowthChart = ref<HTMLDivElement | null>(null)
const revenueChart = ref<HTMLDivElement | null>(null)
const bookingChart = ref<HTMLDivElement | null>(null)
const checkinChart = ref<HTMLDivElement | null>(null)

let memberGrowthChartInstance: echarts.ECharts | null = null
let revenueChartInstance: echarts.ECharts | null = null
let bookingChartInstance: echarts.ECharts | null = null
let checkinChartInstance: echarts.ECharts | null = null

// 热门数据
const popularCourses = ref<PopularCourse[]>([])
const popularCoaches = ref<PopularCoach[]>([])

// 查询参数
const queryParams = reactive({
  startDate: '',
  endDate: '',
  period: 'month'
})

// 获取数据统计概览
const getStatisticsOverview = async () => {
  try {
    const response = await statisticsApi.getStatisticsOverview()
    overview.value = response.data.data
  } catch (error) {
    ElMessage.error('获取数据统计概览失败')
  }
}

// 获取会员增长趋势数据
const getMemberGrowthData = async () => {
  try {
    const response = await statisticsApi.getMemberGrowthData(queryParams)
    const data = response.data.data

    // 准备图表数据
    const dates = data.map(item => item.date)
    const counts = data.map(item => item.count)

    // 渲染图表
    if (memberGrowthChart.value) {
      memberGrowthChartInstance = echarts.init(memberGrowthChart.value)
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: dates
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: counts,
          type: 'line',
          smooth: true,
          areaStyle: {}
        }]
      }
      memberGrowthChartInstance.setOption(option)
    }
  } catch (error) {
    ElMessage.error('获取会员增长趋势数据失败')
  }
}

// 获取收入统计数据
const getRevenueData = async () => {
  try {
    const response = await statisticsApi.getRevenueData(queryParams)
    const data = response.data.data

    // 准备图表数据
    const dates = data.map(item => item.date)
    const amounts = data.map(item => item.amount)

    // 渲染图表
    if (revenueChart.value) {
      revenueChartInstance = echarts.init(revenueChart.value)
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: dates
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: amounts,
          type: 'bar'
        }]
      }
      revenueChartInstance.setOption(option)
    }
  } catch (error) {
    ElMessage.error('获取收入统计数据失败')
  }
}

// 获取课程预约统计数据
const getBookingData = async () => {
  try {
    const response = await statisticsApi.getBookingData(queryParams)
    const data = response.data.data

    // 准备图表数据
    const dates = data.map(item => item.date)
    const counts = data.map(item => item.count)

    // 渲染图表
    if (bookingChart.value) {
      bookingChartInstance = echarts.init(bookingChart.value)
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: dates
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: counts,
          type: 'line',
          smooth: true
        }]
      }
      bookingChartInstance.setOption(option)
    }
  } catch (error) {
    ElMessage.error('获取课程预约统计数据失败')
  }
}

// 获取签到统计数据
const getCheckinData = async () => {
  try {
    const response = await statisticsApi.getCheckinData(queryParams)
    const data = response.data.data

    // 准备图表数据
    const dates = data.map(item => item.date)
    const counts = data.map(item => item.count)

    // 渲染图表
    if (checkinChart.value) {
      checkinChartInstance = echarts.init(checkinChart.value)
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: dates
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: counts,
          type: 'bar'
        }]
      }
      checkinChartInstance.setOption(option)
    }
  } catch (error) {
    ElMessage.error('获取签到统计数据失败')
  }
}

// 获取热门课程统计
const getPopularCourses = async () => {
  try {
    const response = await statisticsApi.getPopularCourses({ limit: 10 })
    popularCourses.value = response.data.data
  } catch (error) {
    ElMessage.error('获取热门课程统计失败')
  }
}

// 获取热门教练统计
const getPopularCoaches = async () => {
  try {
    const response = await statisticsApi.getPopularCoaches({ limit: 10 })
    popularCoaches.value = response.data.data
  } catch (error) {
    ElMessage.error('获取热门教练统计失败')
  }
}

// 初始化所有数据
const initAllData = async () => {
  await Promise.all([
    getStatisticsOverview(),
    getMemberGrowthData(),
    getRevenueData(),
    getBookingData(),
    getCheckinData(),
    getPopularCourses(),
    getPopularCoaches()
  ])
}

// 窗口大小改变时重绘图表
const handleResize = () => {
  if (memberGrowthChartInstance) memberGrowthChartInstance.resize()
  if (revenueChartInstance) revenueChartInstance.resize()
  if (bookingChartInstance) bookingChartInstance.resize()
  if (checkinChartInstance) checkinChartInstance.resize()
}

// 初始化
onMounted(() => {
  initAllData()
  window.addEventListener('resize', handleResize)
})

// 销毁
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  if (memberGrowthChartInstance) memberGrowthChartInstance.dispose()
  if (revenueChartInstance) revenueChartInstance.dispose()
  if (bookingChartInstance) bookingChartInstance.dispose()
  if (checkinChartInstance) checkinChartInstance.dispose()
})
</script>

<style scoped lang="scss">
.statistics-dashboard {
  .overview-section {
    margin-bottom: 20px;

    .stat-card {
      .stat-item {
        display: flex;
        align-items: center;

        .stat-icon {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 15px;

          i {
            font-size: 24px;
            color: white;
          }
        }

        .stat-info {
          .stat-label {
            font-size: 14px;
            color: #606266;
            margin-bottom: 5px;
          }

          .stat-value {
            font-size: 20px;
            font-weight: bold;
            color: #303133;
          }
        }
      }
    }
  }

  .chart-section {
    margin-bottom: 20px;

    .chart-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .chart-container {
        height: 300px;
      }
    }
  }

  .popular-section {
    .popular-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }
  }
}
</style>
